﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace Toolbox
{
    public partial class frmMain : Form
    {
        private ToolboxDataContext dbToolbox = new ToolboxDataContext();
        private bool lHasChanged = false;
        private int nCurrentRowNumber = 0;
        private DataTable tblAuthor = new DataTable("AuthorTable");
        private DataTable tblTags = new DataTable("TagTable");
        private DataTable tblOwner = new DataTable("OwnerTable");
        private bool allAuthor = false;
        private bool allTag = false;
        private bool allOwner = false;
        private bool lPanelResize = false;
              
        public frmMain()
        {
            InitializeComponent();

            if (Properties.Settings.Default.ToolboxConnectionString.Length > 0)
            {
                dbToolbox = new ToolboxDataContext(Properties.Settings.Default.UserToolboxConnectionString);
            }
            else
            {
                string connection = "";
                frmConfig dlgN = new frmConfig();
                dlgN.ShowDialog();

                if (dlgN.DialogResult == DialogResult.OK)
                {
                    connection = dlgN.Connection;
                    dbToolbox = new ToolboxDataContext(connection);
                }
                else
                {
                    this.Close();
                }
            }

            tblTags.Columns.Add("Tag", typeof(string));
            tblAuthor.Columns.Add("Author", typeof(string));
            tblOwner.Columns.Add("Owner", typeof(string));

        }

        private void tsbNew_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Are you sure you want to add a new tool to the toolbox?","Alert",MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                List<Tool> lstTool = dbToolbox.CreateNewTool().ToList<Tool>();
                OpenTool(lstTool[0].ToolID);
            }
        }

        private void OpenTool(int nToolID)
        {
            frmTool newF = new frmTool(nToolID);
            newF.MdiParent = this;
            newF.Show();
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            BindCheckBoxLists();

            lHasChanged = false;

            this.Width = Properties.Settings.Default.Width;
            this.Height = Properties.Settings.Default.Height;
            this.Top = Properties.Settings.Default.Top;
            this.Left = Properties.Settings.Default.Left;
        }

        private void BindCheckBoxLists()
        {                      
            var dsTB = from T in dbToolbox.Tools orderby T.ToolAdded descending select T;
            toolBindingSource.DataSource = dsTB;

            var dsAuthor = (from T in dbToolbox.Tools orderby T.Author select T.Author).Distinct<string>();
            List<string> lAuthor = dsAuthor.ToList<string>();

            var dsTag = (from T in dbToolbox.ToolTags orderby T.Tag select T.Tag).Distinct<string>();
            List<string> lTag = dsTag.ToList<string>();

            var dsOwner = (from T in dbToolbox.Tools orderby T.AddedBy select T.AddedBy).Distinct<string>();
            List<string> lOwner = dsOwner.ToList<string>();

            lstchkAuthor.Items.Clear();
            foreach (var item in lAuthor)
            {
                if (item != null) lstchkAuthor.Items.Add(item.ToString(), true);
            }

            lstchkTags.Items.Clear();
            foreach (var item in lTag)
            {
                if (item != null) lstchkTags.Items.Add(item.ToString(), true);
            }

            lstchkOwner.Items.Clear();
            foreach (var item in lOwner)
            {
                if (item != null) lstchkOwner.Items.Add(item.ToString(), true);
            }        
        }

        private void tsbSave_Click(object sender, EventArgs e)
        {
            try
            {
                frmTool fTool = (frmTool)this.ActiveMdiChild;
                fTool.SaveThisTool();
                DoSearch();
            }
            catch
            {
                // nothing to save
            }            
        }

        private void CancelChanges()
        {
            toolScriptsBindingSource.CancelEdit();
            toolURLsBindingSource.CancelEdit();
            toolNotesBindingSource.CancelEdit();
            toolBindingSource.CancelEdit();

            lHasChanged = false;
        }

        private void toolDataGridView_CurrentCellChanged(object sender, EventArgs e)
        {
            if (toolDataGridView.Rows.Count > 0 & toolDataGridView.CurrentRow != null & toolDataGridView.Focused)
            {
                if ((toolDataGridView.CurrentRow.Index != nCurrentRowNumber) & lHasChanged == true)
                {
                    if (MessageBox.Show("Save any changes?", "Alert", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        //SaveChanges();
                    }
                    else
                    {
                        CancelChanges();
                    }
                }
                nCurrentRowNumber = toolDataGridView.CurrentRow.Index;                
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            DoSearch();
        }

        private void DoSearch()
        {
            dbToolbox = null;
            dbToolbox = new ToolboxDataContext(Properties.Settings.Default.UserToolboxConnectionString);

            tblTags.Clear();
            foreach (object itemChecked in lstchkTags.CheckedItems)
            {
                tblTags.Rows.Add(itemChecked.ToString());
            }

            allTag = (lstchkTags.Items.Count == lstchkTags.CheckedItems.Count);

            tblAuthor.Clear();
            foreach (object itemChecked in lstchkAuthor.CheckedItems)
            {
                tblAuthor.Rows.Add(itemChecked.ToString());
            }

            allAuthor = (lstchkAuthor.Items.Count == lstchkAuthor.CheckedItems.Count);

            tblOwner.Clear();
            foreach (object itemChecked in lstchkOwner.CheckedItems)
            {
                tblOwner.Rows.Add(itemChecked.ToString());
            }

            allOwner = (lstchkOwner.Items.Count == lstchkOwner.CheckedItems.Count);
                      
            ExecuteToolSearch();

            lHasChanged = false;
        }

        private void ExecuteToolSearch()
        {
            List<int> intTools = new List<int>();
            string keywords = "%";

            if (textBox1.Text.Length > 0)
            {
                keywords = textBox1.Text;
            }

            using (SqlConnection cn = new SqlConnection(dbToolbox.Connection.ConnectionString))
            {
                using (SqlCommand cm = new SqlCommand("exec ToolIDSearchByKeyword @keywords, @script, @files, @notes, @allauthor, @author, @alltags, @tags, @allowner, @owner", cn))
                {
                    cm.Parameters.AddWithValue("@keywords", keywords);
                    cm.Parameters.AddWithValue("@script", chkScript.Checked);
                    cm.Parameters.AddWithValue("@files", chkFile.Checked);
                    cm.Parameters.AddWithValue("@notes", chkNotes.Checked);
                    cm.Parameters.AddWithValue("@allauthor", allAuthor);
                    cm.Parameters.AddWithValue("@alltags", allTag);
                    cm.Parameters.AddWithValue("@allowner", allOwner);

                    SqlParameter pAuthor = new SqlParameter();
                    pAuthor.ParameterName = "@author";
                    pAuthor.SqlDbType = System.Data.SqlDbType.Structured;
                    pAuthor.Value = tblAuthor;
                    pAuthor.TypeName = "authortabletype";
                    cm.Parameters.Add(pAuthor);

                    SqlParameter pTag = new SqlParameter();
                    pTag.ParameterName = "@tags";
                    pTag.SqlDbType = System.Data.SqlDbType.Structured;
                    pTag.TypeName = "tagtabletype";
                    pTag.Value = tblTags;
                    cm.Parameters.Add(pTag);

                    SqlParameter pOwner = new SqlParameter();
                    pOwner.ParameterName = "@owner";
                    pOwner.SqlDbType = System.Data.SqlDbType.Structured;
                    pOwner.TypeName = "toolownertabletype";
                    pOwner.Value = tblOwner;
                    cm.Parameters.Add(pOwner);

                    SqlDataAdapter sda = new SqlDataAdapter();

                    dsSearch.ToolDataTable ds = new dsSearch.ToolDataTable();
                    sda.SelectCommand = cm;
                    sda.Fill(ds);

                    toolBindingSource.DataSource = ds;
                }
            }
        }

        private void lnkAuthor_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (lnkAuthor.Text == "Select All")
            {
                for (int i = 0; i < lstchkAuthor.Items.Count; i++)
                {
                    lstchkAuthor.SetItemChecked(i, true);
                }

                lnkAuthor.Text = "Select None";
            }
            else
            {
                for (int i = 0; i < lstchkAuthor.Items.Count; i++)
                {
                    lstchkAuthor.SetItemChecked(i, false);
                }

                lnkAuthor.Text = "Select All";            
            }
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (lnkTag.Text == "Select All")
            {
                for (int i = 0; i < lstchkTags.Items.Count; i++)
                {
                    lstchkTags.SetItemChecked(i, true);
                }

                lnkTag.Text = "Select None";
            }
            else
            {
                for (int i = 0; i < lstchkTags.Items.Count; i++)
                {
                    lstchkTags.SetItemChecked(i, false);
                }

                lnkTag.Text = "Select All";
            }
        }

        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (lHasChanged)
            {
                if (MessageBox.Show("Save changes?", "Alert", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    //SaveChanges();
                }
                else
                {
                    CancelChanges();
                }
            }

            Properties.Settings.Default.Width = this.Width;
            Properties.Settings.Default.Height = this.Height;
            Properties.Settings.Default.Top = this.Top;
            Properties.Settings.Default.Left = this.Left;
            Properties.Settings.Default.Save();
        }

        private void richTextDescription_LinkClicked(object sender, LinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start(e.LinkText);
        }      

        private void tsbAuthors_Click(object sender, EventArgs e)
        {
            dlgAddAuthor dlgN = new dlgAddAuthor();
            dlgN.ShowDialog();

            BindCheckBoxLists();
        }

        private void linkTag_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            MessageBox.Show("Feature not yet available.");
        }

        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                DoSearch();
            }
        }

        private void linkAddScript_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            //SaveChanges();
            toolScriptsBindingSource.AddNew();         
        }

        private void tsbDelete_Click(object sender, EventArgs e)
        {
            try
            {
                if (MessageBox.Show("Are you sure you want to delete this tool?", "Alert", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    frmTool fTool = (frmTool)this.ActiveMdiChild;
                    int nToolToDelete = frmTool.nToolID;
                    dbToolbox.DeleteTool(nToolToDelete);
                    fTool.Close();
                    DoSearch();
                }
            }
            catch
            {
                MessageBox.Show("You must have a tool open to delete.");
            }               

        }

        private void toolDataGridView_DoubleClick(object sender, EventArgs e)
        {
            OpenTool(int.Parse(toolIDTextBox.Text));

            tabForms.SelectedIndex = 0;
            tabForms.SelectedIndex = tabForms.TabCount - 1;
        }

        private void frmMain_MdiChildActivate(object sender, EventArgs e)
        {
            if (this.ActiveMdiChild == null) tabForms.Visible = false;
            // If no any child form, hide tabControl 
            else
            {
                this.ActiveMdiChild.WindowState = FormWindowState.Maximized;
                // Child form always maximized 

                // If child form is new and has no tabPage, 
                // create new tabPage 
                if (this.ActiveMdiChild.Tag == null)
                {
                    // Add a tabPage to tabControl with child 
                    // form caption 
                    TabPage tp = new TabPage(this.ActiveMdiChild.Text);
                    tabForms.SelectedTab = tp;
                    tp.Tag = this.ActiveMdiChild;
                    tp.Parent = tabForms;                    

                    this.ActiveMdiChild.Tag = tp;
                    this.ActiveMdiChild.FormClosed += new FormClosedEventHandler(ActiveMdiChild_FormClosed);
                }

                if (!tabForms.Visible) tabForms.Visible = true;
            }
        }

        private void ActiveMdiChild_FormClosed(object sender, FormClosedEventArgs e)
        {
            ((sender as Form).Tag as TabPage).Dispose();
        }

        private void tabForms_SelectedIndexChanged(object sender, EventArgs e)
        {
            if ((tabForms.SelectedTab != null) &&
                (tabForms.SelectedTab.Tag != null))
            {
                (tabForms.SelectedTab.Tag as Form).Select();                
            }
        }

        private void splitter1_SplitterMoving(object sender, SplitterEventArgs e)
        {
            pnlToolbar.Width = e.SplitY;
        }

        private void splitter1_MouseDown(object sender, MouseEventArgs e)
        {
            lPanelResize = true;
        }

        private void splitter1_MouseUp(object sender, MouseEventArgs e)
        {
            lPanelResize = false;
        }

        private void splitter1_MouseMove(object sender, MouseEventArgs e)
        {
            if (lPanelResize == true)
            {
                pnlToolbar.Width = pnlToolbar.Width += e.X;              
            }
        }

        private void lnkOwner_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (lnkOwner.Text == "Select All")
            {
                for (int i = 0; i < lstchkOwner.Items.Count; i++)
                {
                    lstchkOwner.SetItemChecked(i, true);
                }

                lnkOwner.Text = "Select None";
            }
            else
            {
                for (int i = 0; i < lstchkOwner.Items.Count; i++)
                {
                    lstchkOwner.SetItemChecked(i, false);
                }

                lnkOwner.Text = "Select All";
            }
        }

        private void tsbFindText_Click(object sender, EventArgs e)
        {
            try
            {
                frmTool fTool = (frmTool)this.ActiveMdiChild;
                pnlSearch.Visible = true;
            }
            catch
            {
                // nothing to save
            }  
        }

        private void btnCloseFind_Click(object sender, EventArgs e)
        {
            pnlSearch.Visible = false;
        }

        private void btnFind_Click(object sender, EventArgs e)
        {
            try
            {
                frmTool fTool = (frmTool)this.ActiveMdiChild;
                fTool.FindText(textFind.Text);
            }
            catch
            {
                // nothing to save
            }  
        }

        private void btnReplace_Click(object sender, EventArgs e)
        {
            try
            {
                frmTool fTool = (frmTool)this.ActiveMdiChild;
                fTool.ReplaceText(textFind.Text, textReplace.Text);
            }
            catch
            {
                // nothing to save
            } 
        }

   }
}
